package com.xafc.demo.sys.controller;

import cn.hutool.crypto.SecureUtil;
import com.xafc.demo.security.config.JwtSecurityProperties;
import com.xafc.demo.security.entity.UserDetailEntity;
import com.xafc.demo.sys.model.dto.UserLoginDto;
import com.xafc.demo.framework.result.ApiResult;
import com.xafc.demo.security.utils.CookieUtils;
import com.xafc.demo.security.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/")
public class LoginController {

    @Autowired
    @Qualifier("userDetailServiceImpl")
    private UserDetailsService  userDetailsService;

    @Autowired
    private JwtSecurityProperties jwtSecurityProperties;

    @GetMapping("/login")
    public String login(HttpServletRequest request){
        return "login";
    }

    @ResponseBody
    @PostMapping("/login")
    public ApiResult<UserLoginDto> login(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password
    ) {
        UserDetailEntity userDetails = (UserDetailEntity) this.userDetailsService.loadUserByUsername(username);

        if(userDetails == null){
            return ApiResult.fail("用户不存在");
        }

        if(!SecureUtil.md5(SecureUtil.md5(password) + userDetails.getSalt()).equals(userDetails.getPassword())){
            return ApiResult.fail("密码不正确");
        }

        if (userDetails.getStatus() == 2){
            return ApiResult.fail("你已被锁定");
        }

        if (userDetails.getStatus() == 3){
            return ApiResult.fail("你已被离职");
        }

        // 生成登录的Token
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("userId", userDetails.getId());
        userMap.put("username", userDetails.getUsername());
        final String token = JwtTokenUtil.generateToken(userMap);
        CookieUtils.addCookie(
                request,
                response,
                jwtSecurityProperties.getCookieName(),
                jwtSecurityProperties.getHeadToken() + token,
                jwtSecurityProperties.getNormalExpires()
        );

        // 返回的数据
        UserLoginDto dto = new UserLoginDto();
        dto.setToken(token);
        return ApiResult.success(dto);
    }

//    @GetMapping("/logout")
//    public String logout(HttpServletRequest request,
//                         HttpServletResponse response){
//        CookieUtils.deleteCookie(request, response, jwtSecurityProperties.getCookieName());
//        return "redirect:/login";
//    }
}
